
package vv.lines.core;

import vv.lines.core.context.ContextHolder;
import vv.lines.core.context.IContext;
import vv.lines.store.GameChampion;
import vv.lines.store.IChampionsStore;

import static java.lang.System.exit;
import static vv.lines.utils.TextResources.*;

/**
 *
 * @author vpotapenko
 */
public class Game extends ContextHolder implements IFieldListener, IActionHandler {

    private GameWindow gameWindow;
    private Field field;

    public Game(IContext context) {
        super(context);

        gameWindow = new GameWindow(this, context);
        field = new Field(this, context);

        gameWindow.setField(field);
    }

    public void start() {
        getContext().clearScore();
        scoreChanged();
        gameWindow.updateChampions();
        field.start();
        gameWindow.setVisible(true);
    }

    public void handleAction(ActionId action) {
        switch (action) {
            case NEW_GAME:
                start();
                break;
            case EXIT:
                exit(0);
                break;
            case ABOUT:
                gameWindow.showAbout();
                break;
            case RULES:
                gameWindow.showRules();
                break;
        }
    }

    public void gameLost() {
        getViewFactory().showMessageBox(TITLE, GAME_LOST_MESSAGE);
        checkScore();
    }

    private void checkScore() {
        final IContext context = getContext();
        IChampionsStore championsStore = context.getChampionsStore();
        if (!championsStore.isNewRecord(context.getScore())) return;

        String name = getViewFactory().showInputBox(CHAMPION_MESSAGE, UNNAMED);
        if (name == null) name = UNNAMED;

        GameChampion champion = new GameChampion(name, context.getScore());
        championsStore.addChampion(champion);
        championsStore.save();

        gameWindow.updateChampions();
    }

    public void nextBallsChanged() {
        gameWindow.updateNextBalls();
    }

    public void scoreChanged() {
        gameWindow.updateScore();
    }
}
